import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { List, Card, Input, Button, Modal, Form, InputNumber } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Result from '@/components/Result';
import styles from './Common.less';

const FormItem = Form.Item;

@connect(({ common, loading }) => ({
  common,
  loading: loading.models.list,
}))
@Form.create()
class Common extends PureComponent {
  state = {
    visible: false,
    done: false,
  };

  formLayout = {
    labelCol: { span: 7 },
    wrapperCol: { span: 13 },
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/fetch',
    });
  }

  showModal = () => {
    this.setState({
      visible: true,
      current: undefined,
    });
  };

  showEditModal = (item, index) => {
    this.setState({
      visible: true,
      current: item,
      editableIndex: index,
    });
  };

  handleDone = () => {
    this.setState({
      done: false,
      visible: false,
    });
  };

  handleCancel = () => {
    this.setState({
      visible: false,
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    const { current, editableIndex } = this.state;
    const id = current ? current.id : '';
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setState({
        done: true,
      });
      if (id) {
        dispatch({
          type: 'common/update',
          payload: {
            id,
            ...fieldsValue,
            role: 'general',
            editableIndex,
          },
        });
      } else {
        dispatch({
          type: 'common/add',
          payload: {
            role: 'general',
            ...fieldsValue,
          },
        });
      }
    });
  };

  deleteItem = (id, currentIndex) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/remove',
      payload: { currentIndex, id },
    });
  };

  render() {
    const {
      common: { data },
      loading,
    } = this.props;
    const {
      form: { getFieldDecorator },
    } = this.props;
    const { visible, done, current = {} } = this.state;

    const modalFooter = done
      ? { footer: null, onCancel: this.handleDone }
      : { okText: '保存', onOk: this.handleSubmit, onCancel: this.handleCancel };

    const ListContent = ({
      data: {
        receiverName,
        receiverPhone,
        receiverAddress,
        phone,
        balance,
        'wechatAccount.openId': wechatAccountOpenId,
      },
    }) => (
      <div className={styles.listContent}>
        <div className={styles.listContentItem}>
          <span>收货人</span>
          <p>{receiverName}</p>
        </div>
        <div className={styles.listContentItem}>
          <span>收货电话</span>
          <p>{receiverPhone}</p>
        </div>
        <div className={styles.listContentItem}>
          <span>收货地址</span>
          <p>{receiverAddress}</p>
        </div>
        <div className={styles.listContentItem}>
          <span>手机号码</span>
          <p>{phone}</p>
        </div>
        <div className={styles.listContentItem}>
          <span>余额</span>
          <p>{balance / 100}</p>
        </div>
        <div className={styles.listContentItem}>
          <span>微信ID</span>
          <p>{wechatAccountOpenId}</p>
        </div>
      </div>
    );

    const getModalContent = () => {
      if (done) {
        return (
          <Result
            type="success"
            title="操作成功"
            description="已确认添加该服务商"
            actions={
              <Button type="primary" onClick={this.handleDone}>
                知道了
              </Button>
            }
            className={styles.formResult}
          />
        );
      }
      return (
        <Form onSubmit={this.handleSubmit}>
          <FormItem label="昵称" {...this.formLayout}>
            {getFieldDecorator('nickname', {
              rules: [{ required: true, message: '请输入昵称' }],
              initialValue: current.nickname,
            })(<Input placeholder="请输入" />)}
          </FormItem>
          <FormItem label="姓名" {...this.formLayout}>
            {getFieldDecorator('name', {
              rules: [{ required: true, message: '请输入姓名' }],
              initialValue: current.nickname,
            })(<Input placeholder="请输入" />)}
          </FormItem>
          <FormItem label="手机号" {...this.formLayout}>
            {getFieldDecorator('phone', {
              rules: [{ required: true, message: '请输入手机号' }],
              initialValue: current.phone,
            })(<Input placeholder="请输入" />)}
          </FormItem>
          <FormItem label="余额" {...this.formLayout}>
            {getFieldDecorator('balance', {
              rules: [{ required: true, message: '余额' }],
            })(<InputNumber min={0} max={999999999} />)}
          </FormItem>
          <FormItem label="收货号码" {...this.formLayout}>
            {getFieldDecorator('receiverPhone', {
              rules: [{ required: true, message: '请输入手机号' }],
              initialValue: current.receiverPhone,
            })(<Input placeholder="请输入" />)}
          </FormItem>
          <FormItem label="收货名称" {...this.formLayout}>
            {getFieldDecorator('receiverName', {
              rules: [{ required: true, message: '请输入收货名称' }],
              initialValue: current.receiverName,
            })(<Input placeholder="请输入" />)}
          </FormItem>
          <FormItem label="收货地址" {...this.formLayout}>
            {getFieldDecorator('receiverAddress', {
              rules: [{ required: true, message: '请输入收货地址' }],
              initialValue: current.receiverAddress,
            })(<Input placeholder="请输入" />)}
          </FormItem>
        </Form>
      );
    };
    return (
      <PageHeaderWrapper>
        <div className={styles.standardList}>
          <Card
            className={styles.listCard}
            bordered={false}
            title="普通用户列表"
            style={{ marginTop: 24 }}
            bodyStyle={{ padding: '0 32px 40px 32px' }}
          >
            <List
              size="large"
              loading={loading}
              pagination={{
                ...data.pagination,
                onChange: page => {
                  const { dispatch } = this.props;
                  dispatch({
                    type: 'common/fetch',
                    payload: page,
                  });
                },
              }}
              dataSource={data.list}
              item={data.list}
              renderItem={item => (
                <List.Item>
                  <List.Item.Meta
                    title={`[${item.id}] ${item.nickname ? item.nickname : item.name}`}
                  />
                  <ListContent data={item} />
                </List.Item>
              )}
            />
          </Card>
        </div>
        <Modal
          title={done ? null : `普通用户${current ? '编辑' : '添加'}`}
          className={styles.standardListForm}
          width={640}
          bodyStyle={done ? { padding: '72px 0' } : { padding: '28px 0 0' }}
          destroyOnClose
          visible={visible}
          {...modalFooter}
        >
          {getModalContent()}
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default Common;
